#!/usr/bin/env python3
"""
详细讲解这行代码的逻辑：
return {i: (s - min_score) / (max_score - min_score) for i, s in enumerate(scores)}
"""

def explain_return_statement():
    """
    详细讲解return语句的逻辑
    """
    print("=" * 60)
    print("return语句详细讲解")
    print("=" * 60)
    
    print("\n1. 代码结构分析")
    print("-" * 40)
    print("return {i: (s - min_score) / (max_score - min_score) for i, s in enumerate(scores)}")
    print("\n这是一个字典推导式，包含以下部分：")
    print("• {i: ...} : 字典的键值对结构")
    print("• (s - min_score) / (max_score - min_score) : 归一化公式")
    print("• for i, s in enumerate(scores) : 循环遍历")
    
    print("\n2. enumerate()函数详解")
    print("-" * 40)
    print("enumerate(scores) 返回 (索引, 值) 的元组")
    print("示例：")
    scores = [15.2, 8.7, 22.1, 12.3]
    print(f"scores = {scores}")
    print("enumerate(scores) 产生：")
    for i, s in enumerate(scores):
        print(f"  i={i}, s={s}")
    
    print("\n3. 归一化公式详解")
    print("-" * 40)
    print("公式: (s - min_score) / (max_score - min_score)")
    print("• s : 当前分数")
    print("• min_score : 最小分数")
    print("• max_score : 最大分数")
    print("• 结果范围: [0, 1]")
    
    print("\n4. 具体计算过程")
    print("-" * 40)
    scores = [15.2, 8.7, 22.1, 12.3]
    min_score = min(scores)
    max_score = max(scores)
    
    print(f"分数列表: {scores}")
    print(f"最小值: {min_score}")
    print(f"最大值: {max_score}")
    print(f"分数范围: {max_score - min_score}")
    
    print("\n逐步计算：")
    result = {}
    for i, s in enumerate(scores):
        normalized = (s - min_score) / (max_score - min_score)
        result[i] = normalized
        print(f"  索引{i}: ({s} - {min_score}) / ({max_score} - {min_score}) = {normalized:.3f}")
    
    print(f"\n最终结果: {result}")
    
    print("\n5. 字典推导式 vs 普通循环")
    print("-" * 40)
    print("字典推导式（一行）:")
    print("return {i: (s - min_score) / (max_score - min_score) for i, s in enumerate(scores)}")
    
    print("\n等价的普通循环（多行）:")
    print("result = {}")
    print("for i, s in enumerate(scores):")
    print("    normalized = (s - min_score) / (max_score - min_score)")
    print("    result[i] = normalized")
    print("return result")
    
    print("\n两种写法功能完全相同，但字典推导式更简洁！")


def demonstrate_step_by_step():
    """
    逐步演示计算过程
    """
    print("\n6. 逐步演示")
    print("-" * 40)
    
    # 模拟数据
    scores = [15.2, 8.7, 22.1, 12.3]
    min_score = 8.7
    max_score = 22.1
    
    print(f"输入数据:")
    print(f"  scores = {scores}")
    print(f"  min_score = {min_score}")
    print(f"  max_score = {max_score}")
    
    print(f"\n计算过程:")
    print(f"  分数范围 = {max_score} - {min_score} = {max_score - min_score}")
    
    # 逐步计算
    result = {}
    for i, s in enumerate(scores):
        print(f"\n  处理索引 {i}:")
        print(f"    当前分数 s = {s}")
        print(f"    计算: ({s} - {min_score}) / ({max_score} - {min_score})")
        print(f"    计算: {s - min_score} / {max_score - min_score}")
        print(f"    计算: {s - min_score} / {max_score - min_score} = {(s - min_score) / (max_score - min_score):.3f}")
        
        result[i] = (s - min_score) / (max_score - min_score)
    
    print(f"\n最终结果:")
    print(f"  {result}")
    
    # 验证结果
    print(f"\n验证结果:")
    print(f"  最小值归一化: {result[1]} (应该是0)")
    print(f"  最大值归一化: {result[2]} (应该是1)")
    print(f"  中间值归一化: {result[0]:.3f}, {result[3]:.3f}")


def explain_why_this_works():
    """
    解释为什么这样做有效
    """
    print("\n7. 为什么这样做有效？")
    print("-" * 40)
    
    print("✓ 保持相对关系:")
    print("  如果分数A > 分数B，归一化后仍然 A > B")
    
    print("\n✓ 映射到固定范围:")
    print("  所有分数都被映射到[0,1]区间")
    print("  最小值 → 0")
    print("  最大值 → 1")
    print("  中间值 → 按比例映射")
    
    print("\n✓ 线性变换:")
    print("  归一化是线性变换，不会改变分数的相对顺序")
    
    print("\n✓ 数值稳定性:")
    print("  通过检查 (max_score - min_score) < 1e-9 避免除零错误")


def show_alternative_implementations():
    """
    展示其他实现方式
    """
    print("\n8. 其他实现方式")
    print("-" * 40)
    
    scores = [15.2, 8.7, 22.1, 12.3]
    min_score = min(scores)
    max_score = max(scores)
    
    print("方式1: 字典推导式（当前使用）")
    result1 = {i: (s - min_score) / (max_score - min_score) for i, s in enumerate(scores)}
    print(f"  {result1}")
    
    print("\n方式2: 普通循环")
    result2 = {}
    for i, s in enumerate(scores):
        result2[i] = (s - min_score) / (max_score - min_score)
    print(f"  {result2}")
    
    print("\n方式3: 使用numpy（如果可用）")
    try:
        import numpy as np
        scores_array = np.array(scores)
        normalized = (scores_array - min_score) / (max_score - min_score)
        result3 = {i: normalized[i] for i in range(len(scores))}
        print(f"  {result3}")
    except ImportError:
        print("  numpy未安装，跳过此方式")
    
    print("\n所有方式结果相同！")


def main():
    """
    主函数
    """
    explain_return_statement()
    demonstrate_step_by_step()
    explain_why_this_works()
    show_alternative_implementations()
    
    print("\n" + "=" * 60)
    print("return语句讲解完成！")
    print("=" * 60)


if __name__ == "__main__":
    main()
